#include <stdio.h>
#include <assert.h>
#include <curl/curl.h>
#include "chttpclient.h"


CHttpClient::CHttpClient()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    m_pCurl = curl_easy_init();
    //curl_easy_setopt(m_pCurl, CURLOPT_VERBOSE, 1L);

    CURLcode ret = CURLE_OK;
    ret = curl_easy_setopt(m_pCurl, CURLOPT_TIMEOUT, HC_TIMEOUT);
    assert(ret == CURLE_OK);
    ret = curl_easy_setopt(m_pCurl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
    assert(ret == CURLE_OK);
}

CHttpClient::~CHttpClient()
{
    curl_easy_cleanup(m_pCurl);
    curl_global_cleanup();
}

bool CHttpClient::setProxy(const char *szServer, const int iPort,
                           const char *szUser, const char *szPassword, const char* szDomain)
{
    CURLcode ret = CURLE_OK;
    do {
        // auth type
        ret = curl_easy_setopt(m_pCurl, CURLOPT_PROXYAUTH, CURLAUTH_ANY);
        if (ret != CURLE_OK) {
            break;
        }
        // proxy address
        char szProxy[128] = { 0 };
        sprintf(szProxy, "http://%s:%d", szServer, iPort);
        ret = curl_easy_setopt(m_pCurl, CURLOPT_PROXY, szProxy);
        if (ret != CURLE_OK) {
            break;
        }
        // proxy authentication
        if (szUser != 0) {
            char szAuthentication[128] = { 0 };
            if (szDomain == 0) {
                sprintf(szAuthentication, "%s:%s", szUser, szPassword);
            } else {
                sprintf(szAuthentication, "%s\\%s:%s", szDomain, szUser, szPassword);
            }
            ret = curl_easy_setopt(m_pCurl, CURLOPT_PROXYUSERPWD, szAuthentication);
            if (ret != CURLE_OK) {
                break;
            }
        }
    } while (false);

    return ret == CURLE_OK;
}

bool CHttpClient::getUrlToMem(const char *szUrl, char *szBuffer)
{
    UNUSED_PARAMETER(szUrl);
    UNUSED_PARAMETER(szBuffer);
    fprintf(stderr, "Not implemented...\n");
    return false;
}

bool CHttpClient::getUrlToFile(const char *szUrl, const char *szLocalFilePath)
{
    // open
    FILE *pFile = fopen(szLocalFilePath, "w");
    if (pFile == 0) {
        return false;
    }
    // write
    CURLcode ret = CURLE_OK;
    do {
        ret = curl_easy_setopt(m_pCurl, CURLOPT_URL, szUrl);
        if (ret != CURLE_OK) {
            break;
        }
        ret = curl_easy_setopt(m_pCurl, CURLOPT_WRITEFUNCTION, NULL);
        if (ret != CURLE_OK) {
            break;
        }
        ret = curl_easy_setopt(m_pCurl, CURLOPT_WRITEDATA, pFile);
        if (ret != CURLE_OK) {
            break;
        }
        ret = curl_easy_perform(m_pCurl);
        if (ret != CURLE_OK) {
            break;
        }
    } while (false);
    // close
    fclose(pFile);

    long resCode = 0;
    curl_easy_getinfo(m_pCurl, CURLINFO_RESPONSE_CODE, &resCode);
    if (resCode != 200) {
        return false;
    } else {
        return ret == CURLE_OK;
    }
}
